package com.songlanyun.common.utils.importverify;

import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@Component
public class ImportVerifyHandler implements IExcelVerifyHandler<BaseImportDto> {

    private final ThreadLocal<List<BaseImportDto>> threadLocal = new ThreadLocal<>();

    @Override
    public ExcelVerifyHandlerResult verifyHandler(BaseImportDto inputEntity) {
        StringJoiner joiner = new StringJoiner(",");

        List<BaseImportDto> threadLocalVal = threadLocal.get();
        if (threadLocalVal == null) {
            threadLocalVal = new ArrayList<>();
        }

        for (BaseImportDto dto:threadLocalVal) {
            if (dto.equals(inputEntity)) {
                int lineNumber = dto.getRowNum() + 1;
                joiner.add("数据与第" + lineNumber + "行重复");
                break;
            }
        }

        // 添加本行数据对象到ThreadLocal中
        threadLocalVal.add(inputEntity);
        threadLocal.set(threadLocalVal);
        if (joiner.length() != 0) {
            return new ExcelVerifyHandlerResult(false, joiner.toString());
        }
        return new ExcelVerifyHandlerResult(true);
    }

    public ThreadLocal<List<BaseImportDto>> getThreadLocal() {
        return threadLocal;
    }
}
